import 'package:fluent_ui/fluent_ui.dart';


class RefreshWin extends StatefulWidget {
  final Function onRefresh;
  final Widget child;
  const RefreshWin({super.key, required this.onRefresh, required this.child});

  @override
  State<RefreshWin> createState() => _RefreshWinState();
}

class _RefreshWinState extends State<RefreshWin> {
  final controller = FlyoutController();

  final attachKey = GlobalKey();

  final menuController = FlyoutController();

  final menuAttachKey = GlobalKey();

  final contextController = FlyoutController();

  final contextAttachKey = GlobalKey();

  bool barrierDismissible = true;

  bool dismissOnPointerMoveAway = false;

  bool dismissWithEsc = true;

  FlyoutPlacementMode placementMode = FlyoutPlacementMode.bottomCenter;

  @override
  void initState() {
    super.initState();
    controller.addListener(() {
      if (mounted) setState(() {});
    });
  }

  @override
  void dispose() {
    controller.dispose();
    menuController.dispose();
    contextController.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return FluentTheme(
      data: FluentThemeData(
        brightness: Brightness.dark,
        visualDensity: VisualDensity.standard,
        focusTheme: const FocusThemeData(
          glowFactor: 2.0,
        ),
      ),
      child: FlyoutTarget(
        key: menuAttachKey,
        controller: menuController,
        child: GestureDetector(
          child: widget.child,
          onLongPress: () {
            onLongPress();
          },
          onSecondaryTapUp: (td) {
            onLongPress();
          },
        ),
      ),
    );
  }

  onLongPress (){
    menuController.showFlyout(
      autoModeConfiguration: FlyoutAutoConfiguration(
        preferredMode: placementMode,
      ),
      barrierDismissible: barrierDismissible,
      dismissOnPointerMoveAway: dismissOnPointerMoveAway,
      dismissWithEsc: dismissWithEsc,
      //navigatorKey: rootNavigatorKey.currentState,
      builder: (context) {
        return FluentTheme(
          data: FluentThemeData(
            brightness: Brightness.dark,
            visualDensity: VisualDensity.standard,
            focusTheme: const FocusThemeData(
              glowFactor: 2.0,
            ),
          ),
          child: MenuFlyout(items: [
            MenuFlyoutItem(
              leading: const Icon(FluentIcons.refresh),
              text: const Text('تحديث'),
              onPressed: (){
                widget.onRefresh.call();
                Flyout.of(context).close();
              },
            ),
          ]),
        );
      },
    );
  }
}
